<template>
  <div class="app_main">
    <div class="header">加油站</div>
    <div class="table_box">
      <el-form ref="cuForm" v-loading="formLoading" :model="cuForm" :rules="rules" :disabled="formDisabled">
        <table class="mailTable">
          <tr class="firstTr">
            <td class="firstTd tip_td">
              <span class="tip">*</span>编号
            </td>
            <td class="column content_td" colspan="3">
              <el-form-item prop="release_amount">
                <el-input v-model="cuForm.no" type="text" placeholder="请输入编号" />
              </el-form-item>
            </td>
          </tr>
        </table>
        <table class="mailTable">
          <tr class="firstTr">
            <td class="firstTd" rowspan="3" colspan="2" style="width: 180px;">媒体基本信息</td>
            <td class="firstTd tip_td">
              站点
            </td>
            <td class="column">
              <el-form-item prop="dept_id">
                <el-input v-model="cuForm.name" type="text" placeholder="请输入站点" />
              </el-form-item>
            </td>
            <td class="tip_td">
              资源
            </td>
            <td class="column">
              <el-form-item prop="dept_id">
                <el-select v-model="cuForm.type" style="width: 100%">
                  <el-option
                    v-for="item in jy_options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </td>
          </tr>
          <tr>
            <td class="firstTd tip_td">
              尺寸-宽度
            </td>
            <td class="column">
              <el-form-item prop="dept_id">
                <el-input v-model="cuForm.width" type="text" placeholder="请输入尺寸-宽度" />
              </el-form-item>
            </td>
            <td class="tip_td">
              尺寸-高度
            </td>
            <td class="column">
              <el-form-item prop="dept_id">
                <el-input v-model="cuForm.height" type="text" placeholder="请输入尺寸-高度" />
              </el-form-item>
            </td>
          </tr>
          <tr>
            <td class="firstTd tip_td">
              材质
            </td>
            <td class="column" colspan="3">
              <el-form-item prop="dept_id">
                <el-select v-model="cuForm.dept_3" style="width: 100%">
                  <el-option value="1" label="软膜" />
                  <el-option value="2" label="户外PP" />
                  <el-option value="3" label="刀刻布" />
                </el-select>
              </el-form-item>
            </td>
          </tr>
        </table>
        <!-- 立牌 -->
        <table v-if="cuForm.type == 1" class="mailTable">
          <tr class="firstTr">
            <td class="firstTd" rowspan="4" style="width: 100px;">巡检标准</td>
            <td class="firstTd" rowspan="2" style="width: 80px;">框体</td>
            <td class="tip_td">
              稳固性
            </td>
            <td class="column">
              <el-form-item prop="dept_id">
                <el-select v-model="cuForm.dept_i11" style="width: 100%">
                  <el-option value="1" label="稳固" />
                  <el-option value="2" label="摇晃" />
                </el-select>
              </el-form-item>
            </td>
            <td class="tip_td">
              小耳朵
            </td>
            <td class="column">
              <el-form-item prop="dept_id">
                <el-select v-model="cuForm.dept_i12" style="width: 100%">
                  <el-option value="1" label="完好" />
                  <el-option value="2" label="损坏" />
                </el-select>
              </el-form-item>
            </td>
          </tr>
          <tr>
            <td class="tip_td">
              贴纸
            </td>
            <td class="column">
              <el-form-item prop="dept_id">
                <el-select v-model="cuForm.dept_i14" style="width: 100%">
                  <el-option value="1" label="无" />
                  <el-option value="2" label="有" />
                </el-select>
              </el-form-item>
            </td>
            <td class="tip_td">
              卫生
            </td>
            <td class="column">
              <el-form-item prop="dept_id">
                <el-select v-model="cuForm.dept_i14" style="width: 100%">
                  <el-option value="1" label="干净" />
                  <el-option value="2" label="脏" />
                </el-select>
              </el-form-item>
            </td>
          </tr>
          <tr>
            <td class="firstTd" rowspan="2" style="width: 80px;">画面</td>
            <td class="tip_td">
              方正
            </td>
            <td class="column">
              <el-form-item prop="dept_id">
                <el-select v-model="cuForm.hm1" style="width: 100%">
                  <el-option value="1" label="是" />
                  <el-option value="2" label="否" />
                </el-select>
              </el-form-item>
            </td>
            <td class="tip_td">
              平整
            </td>
            <td class="column">
              <el-form-item prop="dept_id">
                <el-select v-model="cuForm.hm2" style="width: 100%">
                  <el-option value="1" label="是" />
                  <el-option value="2" label="否" />
                </el-select>
              </el-form-item>
            </td>
          </tr>
          <tr>
            <td class="tip_td">
              色泽
            </td>
            <td class="column">
              <el-form-item prop="dept_id">
                <el-select v-model="cuForm.hm3" style="width: 100%">
                  <el-option value="1" label="鲜艳" />
                  <el-option value="2" label="掉色" />
                </el-select>
              </el-form-item>
            </td>
            <td class="tip_td">
              以上
            </td>
            <td class="column">
              <el-form-item prop="dept_id">
                <el-select v-model="cuForm.hm4" style="width: 100%">
                  <el-option value="1" label="全正常" />
                  <el-option value="2" label="有故障" />
                </el-select>
              </el-form-item>
            </td>
          </tr>
        </table>

        <!-- 立柱 -->
        <table v-if="cuForm.type == 2" class="mailTable">
          <tr class="firstTr">
            <td class="firstTd" rowspan="5" style="width: 100px;">巡检标准</td>
            <td class="firstTd" rowspan="3" style="width: 80px;">框体</td>
            <td class="tip_td">
              稳固性
            </td>
            <td class="column">
              <el-form-item prop="dept_id">
                <el-select v-model="cuForm.dept_i11" style="width: 100%">
                  <el-option value="1" label="稳固" />
                  <el-option value="2" label="摇晃" />
                </el-select>
              </el-form-item>
            </td>
            <td class="tip_td">
              小耳朵
            </td>
            <td class="column">
              <el-form-item prop="dept_id">
                <el-select v-model="cuForm.dept_i12" style="width: 100%">
                  <el-option value="1" label="完好" />
                  <el-option value="2" label="损坏" />
                </el-select>
              </el-form-item>
            </td>
          </tr>
          <tr>
            <td class="tip_td">
              贴纸
            </td>
            <td class="column">
              <el-form-item prop="dept_id">
                <el-select v-model="cuForm.dept_i14" style="width: 100%">
                  <el-option value="1" label="无" />
                  <el-option value="2" label="有" />
                </el-select>
              </el-form-item>
            </td>
            <td class="tip_td">
              卫生
            </td>
            <td class="column">
              <el-form-item prop="dept_id">
                <el-select v-model="cuForm.dept_i14" style="width: 100%">
                  <el-option value="1" label="干净" />
                  <el-option value="2" label="脏" />
                </el-select>
              </el-form-item>
            </td>
          </tr>
          <tr>
            <td class="tip_td">
              压边条
            </td>
            <td class="column" colspan="3">
              <el-form-item prop="dept_id">
                <el-select v-model="cuForm.dept_i14" style="width: 100%">
                  <el-option value="1" label="压紧" />
                  <el-option value="2" label="松垮" />
                </el-select>
              </el-form-item>
            </td>
          </tr>
          <tr>
            <td class="firstTd" rowspan="2" style="width: 80px;">画面</td>
            <td class="tip_td">
              方正
            </td>
            <td class="column">
              <el-form-item prop="dept_id">
                <el-select v-model="cuForm.hm1" style="width: 100%">
                  <el-option value="1" label="是" />
                  <el-option value="2" label="否" />
                </el-select>
              </el-form-item>
            </td>
            <td class="tip_td">
              平整
            </td>
            <td class="column">
              <el-form-item prop="dept_id">
                <el-select v-model="cuForm.hm2" style="width: 100%">
                  <el-option value="1" label="是" />
                  <el-option value="2" label="否" />
                </el-select>
              </el-form-item>
            </td>
          </tr>
          <tr>
            <td class="tip_td">
              色泽
            </td>
            <td class="column">
              <el-form-item prop="dept_id">
                <el-select v-model="cuForm.hm3" style="width: 100%">
                  <el-option value="1" label="鲜艳" />
                  <el-option value="2" label="掉色" />
                </el-select>
              </el-form-item>
            </td>
            <td class="tip_td">
              以上
            </td>
            <td class="column">
              <el-form-item prop="dept_id">
                <el-select v-model="cuForm.hm4" style="width: 100%">
                  <el-option value="1" label="全正常" />
                  <el-option value="2" label="有故障" />
                </el-select>
              </el-form-item>
            </td>
          </tr>
        </table>

        <!-- 行架 -->
        <table v-if="cuForm.type == 3" class="mailTable">
          <tr class="firstTr">
            <td class="firstTd" rowspan="5" style="width: 100px;">巡检标准</td>
            <td class="firstTd" rowspan="3" style="width: 80px;">框体</td>
            <td class="tip_td">
              地面支架
            </td>
            <td class="column">
              <el-form-item prop="dept_id">
                <el-select v-model="cuForm.dept_i11" style="width: 100%">
                  <el-option value="1" label="稳固" />
                  <el-option value="2" label="生锈不牢固" />
                </el-select>
              </el-form-item>
            </td>
            <td class="tip_td">
              安全钢丝
            </td>
            <td class="column">
              <el-form-item prop="dept_id">
                <el-select v-model="cuForm.dept_i12" style="width: 100%">
                  <el-option value="1" label="拉紧" />
                  <el-option value="2" label="未拉" />
                  <el-option value="3" label="松垮" />
                </el-select>
              </el-form-item>
            </td>
          </tr>
          <tr>
            <td class="tip_td">
              贴纸
            </td>
            <td class="column">
              <el-form-item prop="dept_id">
                <el-select v-model="cuForm.dept_i14" style="width: 100%">
                  <el-option value="1" label="无" />
                  <el-option value="2" label="有" />
                </el-select>
              </el-form-item>
            </td>
            <td class="tip_td">
              卫生
            </td>
            <td class="column">
              <el-form-item prop="dept_id">
                <el-select v-model="cuForm.dept_i14" style="width: 100%">
                  <el-option value="1" label="干净" />
                  <el-option value="2" label="脏" />
                </el-select>
              </el-form-item>
            </td>
          </tr>
          <tr>
            <td class="tip_td">
              被遮挡
            </td>
            <td class="column" colspan="3">
              <el-form-item prop="dept_id">
                <el-select v-model="cuForm.dept_i14" style="width: 100%">
                  <el-option value="1" label="无" />
                  <el-option value="2" label="有" />
                </el-select>
              </el-form-item>
            </td>
          </tr>
          <tr>
            <td class="firstTd" rowspan="2" style="width: 80px;">画面</td>
            <td class="tip_td">
              方正
            </td>
            <td class="column">
              <el-form-item prop="dept_id">
                <el-select v-model="cuForm.hm1" style="width: 100%">
                  <el-option value="1" label="是" />
                  <el-option value="2" label="否" />
                </el-select>
              </el-form-item>
            </td>
            <td class="tip_td">
              平整
            </td>
            <td class="column">
              <el-form-item prop="dept_id">
                <el-select v-model="cuForm.hm2" style="width: 100%">
                  <el-option value="1" label="是" />
                  <el-option value="2" label="否" />
                </el-select>
              </el-form-item>
            </td>
          </tr>
          <tr>
            <td class="tip_td">
              色泽
            </td>
            <td class="column">
              <el-form-item prop="dept_id">
                <el-select v-model="cuForm.hm3" style="width: 100%">
                  <el-option value="1" label="鲜艳" />
                  <el-option value="2" label="掉色" />
                </el-select>
              </el-form-item>
            </td>
            <td class="tip_td">
              以上
            </td>
            <td class="column">
              <el-form-item prop="dept_id">
                <el-select v-model="cuForm.hm4" style="width: 100%">
                  <el-option value="1" label="全正常" />
                  <el-option value="2" label="有故障" />
                </el-select>
              </el-form-item>
            </td>
          </tr>
        </table>

        <table class="mailTable">

          <tr class="firstTr">
            <td class="tip_td firstTd">
              备注
            </td>
            <td class="column" colspan="3">
              <div style="padding: 10px 0">
                <el-input v-model="cuForm.memo" type="textarea" placeholder="请输入备注" :rows="4" />
              </div>
            </td>
          </tr>
        </table>
      </el-form>
      <span slot="footer" class="dialog-footer" style="margin-left: 100px;">
        <el-button type="primary" @click.native="onSubmit()">保 存</el-button>
        <el-button>完 成</el-button>
      </span>
    </div>
  </div>
</template>

<script>
import FlowBtnRow from '@/components/FlowBtnRow/index'
import pointConfig from '@/components/PointPlanSetting/pointConfig'
import { get_company } from '@/api/system/department'
import { detail as contractDetail, list_by_customer_id, listByCustomerId } from '@/api/contract'
import { actual_delete, begin, detail, media_type_count_amount, pass, remove, return_back, save } from '@/api/saleOrder'
import { formatData } from '@/views/business/contract/util'
import { formatDate, formatDateByFmt, getDaysBetween } from '@/utils/util'
import { add, divide, multiply } from '@/utils/amount'
import { detail as planDetail, listByRelated } from '@/api/business/intention_scheme'
import { company_list_all, list_all } from '@/api/customer/customer'
import { cloneDeep } from 'lodash/lang'
import ContractDialog from '@/views/business/contract/components/ContractDialog'

export default {
  name: 'Detail',
  components: {
    ContractDialog,
    FlowBtnRow,
    pointConfig
  },
  filters: {
    formatDate(time) {
      if (time) {
        return formatDateByFmt(time, 'yyyy年MM月dd日')
      }
    }
  },
  data() {
    return {
      is_created: false,
      formLoading: false,
      jy_options: [{ value: 1, label: '立柱' }, { value: 2, label: '立牌' }, { value: 3, label: '行架' }],
      cuForm: {
        type: 1,
        // 客户id
        customer_id: null,
        // 合同id
        choose_id: null,
        // 点位选择id
        contract_choose_id: null,
        // 日期范围id
        contract_daterange_id: null,
        // 填表日期
        fill_date: formatDate(new Date()),
        // 合同ID
        contract_id: null,
        // 分公司id
        dept_id: null,
        actual_execute_time: [],
        // 实际执行开始时间
        actual_execute_time_start: null,
        // 实际执行结束时间
        actual_execute_time_end: null,
        // 本次发布金额
        release_amount: null,
        // 本次换画面金额
        replace_amount: null,
        // 本次执行金额
        execute_amount: null,
        // 代理公司名称
        proxy_company_name: null,
        // 代理金额
        proxy_amount: null,
        // 被代理公司名称
        proxied_company_name: null,
        // 被代理金额
        proxied_amount: null,
        // 是否置换：1：是，0：否
        need_replace: null,
        // 物品金额
        item_amount: null,
        // 现金金额
        cash_amount: null,
        // 计提额
        accrued_amount: null,
        // 收款时间
        collection_time: null,
        // 是否开发票：1：是，0：否
        need_invoice: null,
        // 备注
        memo: null,
        discount: null,
        // 媒体类型对应数量金额
        billSaleMediaAmountList: [],
        // 代理信息
        billSaleProxyList: [],
        tmpDataList: [],
        proxyInfo: [],
        proxyInfo2: [],
        contractAmount: null,
        dateRangeBeginDate: null,
        dateRangeEndDate: null,
        contractBeginDate: '',
        contractEndDate: '',
        contractName: '',
        contract: null,
        intention_scheme_id: null,
        intention_scheme: null,
        daterange_id: null,
        contract_num: null,
        update_accrued_amount: false,
        billSaleMediaCycle: null

      },
      rules: {
        intention_scheme_id: [
          { required: true, message: '请选择锁位', trigger: 'change' }
        ],
        dept_id: [
          { required: true, message: '请选择所属公司', trigger: 'change' }
        ],
        need_replace: [
          { required: true, message: '请选择是否置换', trigger: 'change' }
        ],
        need_invoice: [
          { required: true, message: '请选择是否开票', trigger: 'change' }
        ],
        collection_time: [
          { required: true, message: '请选择收款时间', trigger: 'change' }
        ],
        customer_id: [
          { required: true, message: '请选择项目', trigger: 'change' }
        ],
        contract_id: [
          { required: true, message: '请选择合同', trigger: 'change' }
        ]
      },
      companyArr: [],
      contractArr: [],
      planArr: [],
      customerArr: [],
      discounted_price: null,
      errorData: {},
      dateRangeArr: [],
      customer_name: null,
      customer_id: null,
      media_name_arr: [],
      media_name_arr2: [],
      discountArr: [],
      media_type_count_amount_arr: [], // 刊例总价
      params: {},
      proxyMediaDetailList: [],
      is_update: false,
      must_include_id: null,
      type: 1,
      centerDialogVisible: false,
      billSaleMediaCycle: {
        day: null,
        cycle_arr: []
      },
      source_contract_id: null
    }
  },
  computed: {
    user_id() {
      return this.$store.state.user.id
    },
    execute_amount() {
      let tmp = 0
      if (this.cuForm.release_amount) {
        tmp = add(this.cuForm.release_amount, tmp)
      }
      if (this.cuForm.replace_amount) {
        tmp = add(this.cuForm.replace_amount, tmp)
      }
      console.log(tmp)
      return tmp
    },
    formDisabled() {
      return this.cuForm.flow_status == 3 || this.cuForm.flow_status == 4
    },
    commission() {
      if (this.execute_amount && this.cuForm.accrued_amount) {
        const a = divide(this.cuForm.accrued_amount, '100')
        const sum = multiply(a, this.execute_amount)
        return sum + '元'
      } else {
        return undefined
      }
    },
    isCompanyCustomer() {
      const find = this.customerArr.find(item => item.id === this.cuForm.customer_id)
      if (find) {
        return find.is_company_customer
      } else {
        return false
      }
    },
    onlyElevatorSmartFrame() { // 是否只有电梯智能框类型
      if (this.media_type_count_amount_arr && this.media_type_count_amount_arr.length) {
        return this.media_type_count_amount_arr.filter(item => item.media_type_id !== 1).length === 0
      } else {
        return false
      }
    },
    totalDay() {
      return this.getDaysBetween(this.cuForm.actual_execute_time_start, this.cuForm.actual_execute_time_end)
    }
  },
  watch: {
    media_type_count_amount_arr: {
      handler(media_type_count_amount_arr) {
        let amount = 0
        if (media_type_count_amount_arr && media_type_count_amount_arr.length > 0) {
          media_type_count_amount_arr.forEach(item => {
            if (item.amount && !isNaN(item.amount)) {
              amount = add(parseInt(item.amount), amount)
            }
          })
        }
        if (this.cuForm.billSaleProxyList && this.cuForm.billSaleProxyList.length > 0) {
          this.cuForm.billSaleProxyList.forEach(item => {
            if (item.proxyMediaDetailList && item.proxyMediaDetailList.length > 0) {
              item.proxyMediaDetailList.forEach(tmp => {
                if (tmp.fill_amount && !isNaN(tmp.fill_amount)) {
                  amount = add(parseInt(tmp.fill_amount), amount)
                }
              })
            }
          })
        }
        if (this.execute_amount !== null && this.execute_amount !== undefined && amount !== 0) {
          const tmp = divide(this.execute_amount, amount).toFixed(4)
          this.cuForm.discount = multiply(tmp, '100')
        } else {
          this.cuForm.discount = 0
        }
      },
      deep: true
    },
    'cuForm.billSaleProxyList': {
      handler(billSaleProxyList) {
        let amount = 0
        if (this.media_type_count_amount_arr && this.media_type_count_amount_arr.length > 0) {
          this.media_type_count_amount_arr.forEach(item => {
            if (item.amount && !isNaN(item.amount)) {
              amount = add(parseInt(item.amount), amount)
            }
          })
        }
        if (billSaleProxyList && billSaleProxyList.length > 0) {
          billSaleProxyList.forEach(item => {
            if (item.proxyMediaDetailList && item.proxyMediaDetailList.length > 0) {
              item.proxyMediaDetailList.forEach(tmp => {
                if (tmp.fill_amount && !isNaN(tmp.fill_amount)) {
                  amount = add(parseInt(tmp.fill_amount), amount)
                }
              })
            }
          })
        }
        if (this.execute_amount !== null && this.execute_amount !== undefined && amount !== 0) {
          const tmp = divide(this.execute_amount, amount).toFixed(4)
          this.cuForm.discount = multiply(tmp, '100')
        } else {
          this.cuForm.discount = 0
        }
      },
      deep: true
    },
    execute_amount(val) {
      this.cuForm.execute_amount = val
      let amount = 0
      if (this.media_type_count_amount_arr && this.media_type_count_amount_arr.length > 0) {
        this.media_type_count_amount_arr.forEach(item => {
          if (item.amount && !isNaN(item.amount)) {
            amount = add(parseInt(item.amount), amount)
          }
        })
      }
      if (this.cuForm.billSaleProxyList && this.cuForm.billSaleProxyList.length > 0) {
        this.cuForm.billSaleProxyList.forEach(item => {
          if (item.proxyMediaDetailList && item.proxyMediaDetailList.length > 0) {
            item.proxyMediaDetailList.forEach(tmp => {
              if (tmp.fill_amount && !isNaN(tmp.fill_amount)) {
                amount = add(parseInt(tmp.fill_amount), amount)
              }
            })
          }
        })
      }
      if (this.execute_amount && amount !== 0) {
        const tmp = divide(this.execute_amount, amount).toFixed(4)
        this.cuForm.discount = multiply(tmp, '100')
      }
    },
    isCompanyCustomer(val) {
      if (val && !this.formDisabled && this.cuForm.flow_status === undefined) {
        this.cuForm.accrued_amount = null
      }
    },
    'billSaleMediaCycle.cycle_arr': {
      handler(val) {
        let day = 0
        if (this.totalDay) {
          day = this.totalDay
          for (let i = 0; i < val.length; i++) {
            if (!isNaN(val[i].value)) {
              day -= val[i].value
            }
          }
        }
        this.billSaleMediaCycle.day = day
      },
      deep: true
    }
  },
  async created() {
    const uuid = this.$route.query.uuid
    const params = this.$store.state.keep.pageParamsMap.get(uuid)
    this.params = params
    console.log(params)
    this.initCompanyArr()
    if (params) {
      if (params.customer_id !== undefined) {
        this.cuForm.customer_id = params.customer_id
      }
      if (params.contract_id !== undefined) {
        this.cuForm.contract_id = params.contract_id
      }
      if (params.plan_id !== undefined) {
        this.cuForm.intention_scheme_id = params.plan_id
      }
      if (params.is_create == true) {
        this.is_created = true
        this.initCustomerArr(true)
        if (params.is_update) {
          this.formLoading = true
          list_by_customer_id({ customerId: this.cuForm.customer_id }).then(res => {
            this.contractArr = res.data
            const find = this.contractArr.find(item => item.id === this.cuForm.contract_id)
            if (find) {
              this.cuForm.contract_num = find.contract_num
              this.proxyMediaDetailList = []
              this.cuForm.billSaleProxyList = []
              this.cuForm.contract_id = find.id
              this.cuForm.dept_id = find.part_b_id
              this.discounted_price = find.discounted_price
              this.cuForm.contract = find
              contractDetail(find.id).then(res => {
                this.proxyMediaDetailList = res.data.proxyMediaDetailList
                this.cuForm.billSaleProxyList.push({
                  proxy_company_name: null,
                  proxy_amount: null,
                  proxyMediaDetailList: cloneDeep(this.proxyMediaDetailList)
                })
                listByRelated({ related_id: params.source_sale_id, related_type: 2 }).then(res => {
                  this.planArr = res.data
                  this.cuForm.intention_scheme = this.planArr.find(item => item.id === this.cuForm.intention_scheme_id)
                  this.planChange(this.cuForm.intention_scheme)
                  media_type_count_amount({
                    customerId: this.cuForm.customer_id,
                    dateRangeId: this.cuForm.intention_scheme.daterange_id
                  }).then(res => {
                    this.media_type_count_amount_arr = res.data.filter(item => item.spec_count != 0)
                    for (let i = 0; i < this.media_type_count_amount_arr.length; i++) {
                      if (this.media_type_count_amount_arr[i].media_type_id !== 1) {
                        this.media_type_count_amount_arr[i].amount = null
                      }
                    }
                    this.cuForm.billSaleMediaAmountList = res.data.filter(item => item.spec_count != 0).map(item => {
                      return {
                        media_type_spec_id: item.media_type_spec_id,
                        media_type_spec_price_id: item.media_type_spec_price_id,
                        name: item.name,
                        media_count: item.spec_count,
                        fill_amount: null,
                        has_price_day: item.has_price_day,
                        has_price_week: item.has_price_week,
                        has_price_month: item.has_price_month,
                        price: null
                      }
                    })
                    this.formLoading = false
                  }).catch(() => {
                    this.formLoading = false
                  })
                })
              })
            }
          })
        }
      }
      if (params.is_update) {
        this.is_update = true
      }
      if (params.type !== undefined) {
        this.type = params.type
      }
      if (params.id || params.handle_param) {
        let id = null
        if (params.id) {
          id = params.id
        } else {
          id = params.handle_param.id
        }
        this.formLoading = true
        await detail({ id: id }).then(res => {
          this.cuForm = res.data
          this.type = res.data.type
          this.must_include_id = this.cuForm.intention_scheme_id
          this.source_contract_id = this.cuForm.contract_id
          if (this.cuForm.intention_scheme_related_type === 2) {
            this.is_update = true
          }
          if (!res.data.is_old_data) {
            if (!this.cuForm.billSaleMediaCycle) {
              this.cuForm.billSaleMediaCycle = {
                day: null,
                cycle_arr: []
              }
            }
            if (!this.cuForm.billSaleMediaCycle.cycle_arr || this.cuForm.billSaleMediaCycle.cycle_arr.length === 0) {
              this.cuForm.billSaleMediaCycle.cycle_arr = []
            }
          }
          this.media_type_count_amount_arr = res.data.mediaPriceList.filter(item => item.spec_count != 0)
          this.$set(this.cuForm, 'billSaleMediaAmountList', cloneDeep(this.cuForm.mediaAmountVOList))
          this.$set(this.cuForm, 'billSaleProxyList', cloneDeep(this.cuForm.billSaleProxies))
          this.cuForm.tmpDataList = formatData(res)
        })
        const flowStatus = this.cuForm.flow_status
        if (flowStatus == 3 || flowStatus == 4) {
          this.initCustomerArr()
        } else {
          this.initCustomerArr(true)
        }
        await listByCustomerId({ customerId: this.cuForm.customer_id }).then(res => {
          this.contractArr = res.data
        })
        this.cuForm.contract = this.contractArr.find(item => item.id === this.cuForm.contract_id)
        this.discounted_price = ((this.cuForm.contract || {}).discounted_price || 0)
        listByRelated({
          related_id: this.cuForm.intention_scheme_related_id,
          related_type: this.cuForm.intention_scheme_related_type,
          must_include_id: this.cuForm.contract_id === this.source_contract_id ? this.must_include_id : null
        }).then(res => {
          this.planArr = res.data
          this.cuForm.intention_scheme = this.planArr.find(item => item.id === this.cuForm.intention_scheme_id)
          this.planChange(this.cuForm.intention_scheme)
          this.formLoading = false
        })
      }
    }
  },
  methods: {
    // 根据销售单id，设置
    setSourceBillSaleMediaCycle(sale_id, daterange_id) {
      detail({
        id: sale_id
      }).then(res => {
        if (!res.data.is_old_data) {
          if (!this.cuForm.billSaleMediaCycle) {
            this.cuForm.billSaleMediaCycle = {
              day: null,
              cycle_arr: []
            }
          }
          if (!this.cuForm.billSaleMediaCycle.cycle_arr || this.cuForm.billSaleMediaCycle
            .cycle_arr.length === 0) {
            this.cuForm.billSaleMediaCycle.cycle_arr = []
          }
        }
        media_type_count_amount({
          customerId: this.cuForm.customer_id,
          dateRangeId: daterange_id
        }).then(res => {
          this.media_type_count_amount_arr = res.data.filter(item => item.spec_count != 0)
          for (let i = 0; i < this.media_type_count_amount_arr.length; i++) {
            if (this.media_type_count_amount_arr[i].media_type_id !== 1) {
              this.media_type_count_amount_arr[i].amount = null
            }
          }
          this.cuForm.billSaleMediaAmountList = res.data.filter(item => item.spec_count != 0)
            .map(item => {
              return {
                media_type_spec_id: item.media_type_spec_id,
                media_type_spec_price_id: item.media_type_spec_price_id,
                name: item.name,
                media_count: item.spec_count,
                fill_amount: null,
                has_price_day: item.has_price_day,
                has_price_week: item.has_price_week,
                has_price_month: item.has_price_month,
                price: null
              }
            })
        }).catch(() => {
        })
      })
    },
    /**
     * 初始化子公司数组
     */
    initCompanyArr() {
      get_company().then(res => {
        this.companyArr = res.data
      })
    },
    /**
     * 检验金额
     * @returns {boolean}
     */
    handlerCheck() {
      // 校验物品金额和消费金额
      const reg = /(^[1-9]{1}[0-9]*$)|(^[0-9]*\.[0-9]{2}$)/
      let number = 0
      if (this.cuForm.item_amount) {
        if (!reg.test(this.cuForm.item_amount)) {
          this.$message.error('物品金额不合法')
          return false
        }
        number = add(number, this.cuForm.item_amount)
      }
      if (this.cuForm.cash_amount) {
        if (!reg.test(this.cuForm.cash_amount)) {
          this.$message.error('消费金额不合法')
          return false
        }
        number = add(number, this.cuForm.cash_amount)
      }
      if (this.cuForm.execute_amount < number) {
        this.$message.error('消费金额加上物品金额不能大于本次执行金额,请调整')
        return false
      }
      // 校验代理信息
      if (this.cuForm.billSaleProxyList.length === 0) {
        return true
      } else {
        let sum = 0
        let temp = 0
        for (let i = 0; i < this.cuForm.billSaleProxyList.length; i++) {
          const tmp = this.cuForm.billSaleProxyList[i]
          if (!isNaN(tmp.proxy_amount) && tmp.proxy_amount) {
            sum = add(sum, tmp.proxy_amount)
          }
          if (tmp.proxyMediaDetailList) {
            for (let j = 0; j < tmp.proxyMediaDetailList.length; j++) {
              if (!isNaN(tmp.proxyMediaDetailList[j].amount) && tmp.proxyMediaDetailList[j].amount) {
                temp = add(temp, tmp.proxyMediaDetailList[j].amount)
              }
            }
            // if (temp != tmp.proxy_amount && tmp.proxy_amount !== null && tmp.proxy_amount !== '') {
            //   this.$message.error('代媒体形式' + (i + 1) + '中的媒体金额不等于该媒体形式的代理公司的代理金额，请调整')
            //   return false
            // }
          }
        }
        let sum2 = 0
        this.cuForm.billSaleMediaAmountList.forEach(item => {
          if (!isNaN(item.fill_amount) && item.fill_amount) {
            sum2 = add(sum2, item.fill_amount)
          }
        })
        const sum3 = add(sum2, temp)
        if (sum3 == this.execute_amount) {
          return true
        } else {
          this.$message.error('【代媒体形式的媒体总金额：' + temp + '元】加上【媒体形式总额：' + sum2 + '元】不等于【执行金额：' + this.execute_amount + '元】，请调整')
          return false
        }
      }
    },
    save() {
      if ((this.cuForm.release_amount == null || this.cuForm.release_amount == '') && (this.cuForm.replace_amount == null || this.cuForm.replace_amount == '')) {
        this.$message.error('发布金额和换画金额不能都为空')
        return
      }
      if (this.handlerCheck()) {
        let flag = false
        if (!this.cuForm.is_old_data) {
          flag = this.check()
        } else {
          flag = true
        }
        if (flag) {
          const loading = this.$loading({
            lock: true,
            text: '加载中',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          const req = cloneDeep(this.cuForm)
          req.type = this.type
          if (!this.onlyElevatorSmartFrame) {
            req.billSaleMediaCycleDTO = cloneDeep(this.cuForm.billSaleMediaCycle)
          }
          req.mediaPriceList = []
          this.media_type_count_amount_arr.forEach(item => {
            req.mediaPriceList.push({
              media_type_spec_price_id: item.media_type_spec_price_id,
              price: item.amount
            })
          })
          save(req).then(res => {
            if (res.data == null) {
              this.$message({
                message: '操作成功',
                type: 'success'
              })
              this.closeThisPage()
            }
            loading.close()
          }).catch(() => {
            loading.close()
          })
        }
      }
    },
    submit() {
      if ((this.cuForm.release_amount == null || this.cuForm.release_amount === '') && (this.cuForm.replace_amount == null || this.cuForm.replace_amount === '')) {
        this.$message.error('发布金额和换画金额不能都为空')
        return
      }
      if (this.handlerCheck()) {
        let flag = false
        if (!this.cuForm.is_old_data) {
          flag = this.check()
        } else {
          flag = true
        }
        if (flag) {
          const loading = this.$loading({
            lock: true,
            text: '加载中',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          const req = cloneDeep(this.cuForm)
          req.type = this.type
          req.mediaPriceList = []
          if (!this.onlyElevatorSmartFrame) {
            req.billSaleMediaCycleDTO = cloneDeep(this.cuForm.billSaleMediaCycle)
          }
          this.media_type_count_amount_arr.forEach(item => {
            req.mediaPriceList.push({
              media_type_spec_price_id: item.media_type_spec_price_id,
              price: item.amount
            })
          })
          begin(req).then(res => {
            if (res.data == null) {
              this.$message({
                message: '操作成功',
                type: 'success'
              })
              this.closeThisPage()
            }
            loading.close()
          }).catch(() => {
            loading.close()
          })
        }
      }
    },
    pass(opinion) {
      const loading = this.$loading({
        lock: true,
        text: '加载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      pass({
        id: this.cuForm.id,
        wf_check_opinion: opinion,
        accrued_amount: this.cuForm.update_accrued_amount ? this.cuForm.accrued_amount : null
      }).then(res => {
        this.closeThisPage()
        loading.close()
      }).catch(() => {
        loading.close()
      })
    },
    returnBack(opinion) {
      const loading = this.$loading({
        lock: true,
        text: '加载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      return_back({ id: this.cuForm.id, wf_check_opinion: opinion }).then(res => {
        this.closeThisPage()
        loading.close()
      }).catch(() => {
        loading.close()
      })
    },
    remove() {
      const loading = this.$loading({
        lock: true,
        text: '加载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      remove({ id: this.cuForm.id }).then(res => {
        this.closeThisPage()
        loading.close()
      }).catch(() => {
        loading.close()
      })
    },
    actualDelete() {
      const loading = this.$loading({
        lock: true,
        text: '加载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      actual_delete({ id: this.cuForm.id }).then(res => {
        this.closeThisPage()
        loading.close()
      }).catch(() => {
        loading.close()
      })
    },
    // actualExecuteTimeChange(date) {
    //   if (date) {
    //     this.cuForm.actual_execute_time_start = date[0]
    //     this.cuForm.actual_execute_time_end = date[1]
    //   }
    // },
    closeThisPage() {
      this.$store.dispatch('tagsView/closeCurPage')
    },
    /**
     * 增加代理信息
     * @param type
     */
    addProxy(type) {
      this.cuForm.billSaleProxyList.push({
        proxy_company_name: null,
        proxy_amount: null,
        proxyMediaDetailList: cloneDeep(this.proxyMediaDetailList)
      })
    },
    addProxyDetail(arr) {
      arr = arr || []
      arr.push({
        amount: null,
        duration: null,
        fill_amount: null,
        media_type_spec: null,
        proxy_media_type: null,
        quantity: null
      })
    },
    removeProxy(index, arr) {
      arr.splice(index, 1)
    },
    removeProxyMain(index) {
      this.cuForm.billSaleProxyList.splice(index, 1)
    },
    /**
     * 客户选择框改变
     */
    customerChange(id) {
      this.clearContractId()
      listByCustomerId({ customerId: id }).then(res => {
        this.contractArr = res.data
      })
    },
    /**
     * 合同客户名称change事件
     * @param data
     */
    contractChange(data) {
      this.clearPlanId()
      this.cuForm.contract_num = data.contract_num
      this.proxyMediaDetailList = []
      this.cuForm.billSaleProxyList = []
      this.cuForm.contract_id = data.id
      this.cuForm.dept_id = data.part_b_id
      this.discounted_price = data.discounted_price
      this.initPlanList(data.id)
      contractDetail(data.id).then(res => {
        this.proxyMediaDetailList = res.data.proxyMediaDetailList
        this.cuForm.billSaleProxyList.push({
          proxy_company_name: null,
          proxy_amount: null,
          proxyMediaDetailList: cloneDeep(this.proxyMediaDetailList)
        })
      })
    },
    clearPlanId() {
      if (this.cuForm.intention_scheme !== null) {
        this.cuForm.intention_scheme = null
      }
      this.cuForm.choose_id = null
      this.cuForm.daterange_id = null
      if (this.cuForm.intention_scheme_id !== null) {
        this.cuForm.intention_scheme_id = null
      }
      this.planArr = []
      this.cuForm.actual_execute_time_start = null
      this.cuForm.actual_execute_time_end = null
    },
    clearContractId() {
      this.cuForm.contract_id = null
      this.cuForm.contract = null
      this.contractArr = []
      this.discounted_price = null
      this.billSaleProxyList = []
      this.cuForm.billSaleProxyList = []
      this.cuForm.contract_num = null
      this.clearPlanId()
    },
    /**
     * 获取方案列表
     */
    initPlanList(related_id) {
      listByRelated({
        related_id: related_id,
        related_type: 1,
        must_include_id: this.cuForm.contract_id === this.source_contract_id ? this.must_include_id : null,
        type: this.type
      }).then(res => {
        this.planArr = res.data
        this.cuForm.intention_scheme = this.planArr.find(item => item.id === this.cuForm.intention_scheme_id)
      })
    },
    async planChange(data, flag = false) {
      this.cuForm.choose_id = data.choose_id
      this.cuForm.intention_scheme_id = data.id
      this.cuForm.daterange_id = data.daterange_id
      this.cuForm.actual_execute_time_start = data.daterange_start_at
      this.cuForm.actual_execute_time_end = data.daterange_end_at
      let loading
      if (flag) {
        loading = this.$loading({
          lock: true,
          text: '加载中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
      }
      await planDetail({ id: data.id }).then(res => {
        this.cuForm.tmpDataList = formatData(res)
      }).catch(() => {
        loading.close()
      })
      if (flag) {
        this.cuForm.billSaleMediaCycle = null
      }
      if (flag) {
        media_type_count_amount({ customerId: this.cuForm.customer_id, dateRangeId: data.daterange_id }).then(res => {
          this.media_type_count_amount_arr = res.data.filter(item => item.spec_count != 0)
          for (let i = 0; i < this.media_type_count_amount_arr.length; i++) {
            if (this.media_type_count_amount_arr[i].media_type_id !== 1) {
              this.media_type_count_amount_arr[i].amount = null
            }
          }
          this.cuForm.billSaleMediaAmountList = res.data.filter(item => item.spec_count != 0).map(item => {
            return {
              media_type_spec_id: item.media_type_spec_id,
              media_type_spec_price_id: item.media_type_spec_price_id,
              name: item.name,
              media_count: item.spec_count,
              fill_amount: null,
              has_price_day: item.has_price_day,
              has_price_week: item.has_price_week,
              has_price_month: item.has_price_month,
              price: null
            }
          })
          loading.close()
        }).catch(() => {
          loading.close()
        })
      }
    },
    initCustomerArr(flag = false) {
      if (flag) {
        list_all().then(res => {
          this.customerArr = res.data
        })
      } else {
        company_list_all().then(res => {
          this.customerArr = res.data
        })
      }
    },
    /**
     * 获取时间间隔 开始日期也算一天
     * @param startDate
     * @param endDate
     * @returns {number}
     */
    getDaysBetween(startDate, endDate) {
      const number = getDaysBetween(startDate, endDate) + 1
      return isNaN(number) ? '选择方案后自动计算' : number
    },
    /**
     * 填写金额改变时修改对应类型的值
     * @param item
     * @param type
     * @param fill_amount
     */
    fillAmountChange(item, type, fill_amount) {
      if (fill_amount) {
        // 计算出每天的价格
        const time = this.getDaysBetween(this.cuForm.actual_execute_time_start, this.cuForm.actual_execute_time_end)
        let num = divide(fill_amount, multiply(item.media_count, time))
        if (num.toString().indexOf('.') > -1) {
          num = parseFloat(num.toString().substr(0, num.toString().indexOf('.') + 5))
        }
        if (type === 'day') {
          item.day_price = num.toFixed(2)
          return item.day_price
        } else if (type === 'week') {
          item.week_price = multiply(num, 7).toFixed(2)
          return item.week_price
        } else {
          item.month_price = multiply(num, 30).toFixed(2)
          return item.month_price
        }
      } else {
        return null
      }
    },
    showContractDialog() {
      this.$refs.contractDialog.open()
    },
    showCycleDialog() {
      this.centerDialogVisible = true
      this.billSaleMediaCycle = cloneDeep(this.cuForm.billSaleMediaCycle)
      if (!this.billSaleMediaCycle) {
        this.billSaleMediaCycle = {
          day: null,
          cycle_arr: []
        }
      }
      this.billSaleMediaCycle.cycle_arr = this.billSaleMediaCycle.cycle_arr.map(item => {
        return {
          value: item
        }
      })
    },
    closeCycleDialog() {
      this.billSaleMediaCycle = {
        day: null,
        cycle_arr: []
      }
    },
    saveCycle() {
      this.$refs.cycleForm.validate(flag => {
        if (flag) {
          if (this.billSaleMediaCycle.day >= 0) {
            this.cuForm.billSaleMediaCycle = cloneDeep(this.billSaleMediaCycle)
            this.cuForm.billSaleMediaCycle.cycle_arr = this.cuForm.billSaleMediaCycle.cycle_arr.map(item => {
              return item.value
            })
            this.centerDialogVisible = false
            // 计算价格
            this.media_type_count_amount_arr.forEach(item => {
              console.log(item)
              if (item.media_type_id !== 1) {
                if (item.has_price_month) {
                  if (this.billSaleMediaCycle.cycle_arr && this.billSaleMediaCycle.cycle_arr.length) {
                    let amount = multiply(item.month_price, this.billSaleMediaCycle.cycle_arr.length)
                    amount = add(amount, multiply(item.day_price, this.billSaleMediaCycle.day))
                    item.amount = multiply(amount, item.spec_count)
                  } else {
                    item.amount = multiply(multiply(item.day_price, this.totalDay), item.spec_count)
                  }
                } else {
                  item.amount = multiply(multiply(item.day_price, this.totalDay), item.spec_count)
                }
              }
            })
          } else {
            this.$message.error('剩余天数不能小于0')
          }
        }
      })
    },
    check() {
      if (this.onlyElevatorSmartFrame) {
        return true
      } else {
        for (let i = 0; i < this.media_type_count_amount_arr.length; i++) {
          if (!this.media_type_count_amount_arr[i].amount) {
            this.$message.error('刊例总价有媒体类型的价格为空，请先设置周期')
            return false
          }
        }
        return true
      }
    }
  }
}
</script>

<style scoped>
.mailTable {
  width: 90%;
  font-size: 14px;
  margin: 0 auto 10px auto;
  border-collapse: collapse;
}

.mailTable tr td {
  height: 60px;
  line-height: 35px;
  box-sizing: border-box;
  padding: 0 10px;
  border-bottom: 1px solid #E6EAEE;
  border-right: 1px solid #E6EAEE;
  text-align: center;
}

.firstTr td {
  border-top: 1px solid #E6EAEE;
}

.firstTd {
  border-left: 1px solid #E6EAEE;
}

.mailTable tr td.column {
  text-align: center;
  /*border: 1px solid #8c939d;*/
}

.header {
  text-align: center;
  font-size: 25px;
  font-weight: bold;
  margin: 10px auto;
}

.tip {
  color: red;
}

/deep/ .mailTable .el-form-item {
  margin-bottom: 0;
}

/deep/ .mailTable .el-form-item__content {
  line-height: 0;
}

.tip_td {
  width: 10% !important;
  padding: 0 20px !important;
  background-color: #F5F7FA;
  font-weight: bold;
}

.proxyTable {
  width: 100%;
  font-size: 12px;
}

.proxyTable tr td {
  line-height: 23px;
  padding: 6px 0;
  height: auto;
}

/deep/ .el-input.is-disabled .el-input__inner {
  background-color: white;
  color: black;
}

/deep/ .el-textarea.is-disabled .el-textarea__inner {
  background-color: white;
  color: black;
}

/deep/ .el-radio__input.is-disabled + span.el-radio__label {
  color: black;
}

/deep/ .el-radio__input.is-checked .el-radio__inner {
  border-color: #409EFF;
  background: #409EFF
}

/deep/ .el-radio__input.is-disabled.is-checked .el-radio__inner::after {
  width: 4px;
  height: 4px;
  border-radius: 100%;
  background-color: #FFF;
}

.content_td {
  width: 40%;
}

@media screen and (max-width: 1920px) {
  /*当屏幕尺寸小于600px时，应用下面的CSS样式*/
  .mailTable {
    width: 95%;
    font-size: 14px;
    margin: 0 auto 10px auto;
    border-collapse: collapse;
  }
}

@media screen and (max-width: 1600px) {
  /*当屏幕尺寸小于600px时，应用下面的CSS样式*/
  .mailTable {
    width: 99%;
    font-size: 14px;
    margin: 0 auto 10px auto;
    border-collapse: collapse;
  }
}
</style>
